package com.example.electricbicycle.controller;

import com.example.electricbicycle.dao.SalesmanDAO;
import com.example.electricbicycle.po.User;
import com.example.electricbicycle.po.PurchaseOrder;
import com.example.electricbicycle.po.Vehicle;
import com.example.electricbicycle.service.PurchaseService;
import com.example.electricbicycle.service.PurchaseServiceImpl;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/purchase/*")
public class PurchaseServlet extends HttpServlet {

    private PurchaseService purchaseService = new PurchaseServiceImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getPathInfo();
        HttpSession session = request.getSession();


        User currentUser = (User) session.getAttribute("currentUser");

        // 验证用户登录和角色权限（业务员role=0）
        if (currentUser == null || currentUser.getRole() != 0) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        try {
            if (action == null) {
                listOrders(request, response, currentUser.getId(), null);
                return;
            }

            switch (action) {
                case "/list":
                    String filterType = request.getParameter("type");
                    listOrders(request, response, currentUser.getId(), filterType);
                    break;
                case "/new":
                    showNewForm(request, response);
                    break;
                case "/edit":
                    showEditForm(request, response);
                    break;
                case "/view":
                    viewOrder(request, response);
                    break;
                case "/delete":
                    deleteOrder(request, response);
                    break;
                default:
                    listOrders(request, response, currentUser.getId(), null);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("errorMessage", "系统错误：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/purchase/list");
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String action = request.getPathInfo();
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");

        if (currentUser == null || currentUser.getRole() != 0) {
            response.sendRedirect(request.getContextPath() + "/login.jsp");
            return;
        }

        try {
            switch (action) {
                case "/save":
                    saveOrder(request, response, currentUser);
                    break;
                case "/update":
                    updateOrder(request, response);
                    break;
                default:
                    listOrders(request, response, currentUser.getId(), null);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("errorMessage", "操作失败：" + e.getMessage());
            response.sendRedirect(request.getContextPath() + "/purchase/list");
        }
    }

    private void listOrders(HttpServletRequest request, HttpServletResponse response,
                            int salesmanId, String filterType)
            throws ServletException, IOException {

        // 获取统计数据
        int totalOrders = purchaseService.getTotalOrderCount(salesmanId);
        int pendingOrders = purchaseService.getPendingOrderCount(salesmanId);
        int approvedOrders = purchaseService.getApprovedOrderCount(salesmanId);

        request.setAttribute("totalOrders", totalOrders);
        request.setAttribute("pendingOrders", pendingOrders);
        request.setAttribute("approvedOrders", approvedOrders);

        // 根据过滤类型获取订单列表
        List<PurchaseOrder> orders;
        String title = "所有进车订单";

        if ("pending".equals(filterType)) {
            orders = purchaseService.getFilteredOrders(salesmanId, "pending");
            title = "待审核订单";
        } else if ("approved".equals(filterType)) {
            orders = purchaseService.getFilteredOrders(salesmanId, "approved");
            title = "已审核订单";
        } else {
            orders = purchaseService.getAllOrdersForSalesman(salesmanId);
            filterType = "all";
        }

        for (PurchaseOrder order : orders) {
            if (order.getVehicle() == null) {
                Vehicle vehicle = purchaseService.getVehicleById(order.getV_id());
                order.setVehicle(vehicle);
            }
        }

        request.setAttribute("orders", orders);
        request.setAttribute("pageTitle", title);
        request.setAttribute("filterType", filterType);

        request.getRequestDispatcher("/salesman/list.jsp").forward(request, response);
    }

    private void showNewForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            // 获取所有车辆信息
            List<Vehicle> vehicles = purchaseService.getAllVehicles();
            request.setAttribute("vehicles", vehicles);
            request.getRequestDispatcher("/salesman/new.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.getSession().setAttribute("errorMessage", "加载车辆信息失败: " + e.getMessage());
            request.getRequestDispatcher("/salesman/new.jsp").forward(request, response);
        }
    }

    private void showEditForm(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        PurchaseOrder order = purchaseService.getPurchaseOrderById(id);
        User currentUser = (User) request.getSession().getAttribute("currentUser");

        // 验证订单是否存在、是否可编辑、是否属于当前业务员
        if (order != null &&
                purchaseService.canEditOrder(id) &&
                order.getUser_id() == currentUser.getId()) {

            // 获取车辆详情并设置到订单中
            Vehicle vehicle = purchaseService.getVehicleById(order.getV_id());
            order.setVehicle(vehicle);

            request.setAttribute("order", order);
            request.setAttribute("vehicles", purchaseService.getAllVehicles());
            request.getRequestDispatcher("/salesman/form.jsp").forward(request, response);
        } else {
            request.getSession().setAttribute("errorMessage", "无法编辑该订单：订单不存在或已被审核");
            response.sendRedirect(request.getContextPath() + "/purchase/list");
        }
    }

    private void viewOrder(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SQLException {
        int id = Integer.parseInt(request.getParameter("id"));
        PurchaseOrder order = purchaseService.getPurchaseOrderById(id);
        User currentUser = (User) request.getSession().getAttribute("currentUser");

        if (order != null && order.getUser_id() == currentUser.getId()) {
            // 加载关联的车辆信息
            Vehicle vehicle = purchaseService.getVehicleById(order.getV_id());
            order.setVehicle(vehicle);
            SalesmanDAO salesmanDAO = new SalesmanDAO();
            order.setSalesman(salesmanDAO.getSalesmanById(order.getUser_id()));

            request.setAttribute("order", order);
            request.setAttribute("vehicle", vehicle);
            request.getRequestDispatcher("/salesman/view.jsp").forward(request, response);
        } else {
            request.getSession().setAttribute("errorMessage", "无法查看该订单");
            response.sendRedirect(request.getContextPath() + "/purchase/list");
        }
    }

    private void deleteOrder(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        User currentUser = (User) request.getSession().getAttribute("currentUser");
        PurchaseOrder order = purchaseService.getPurchaseOrderById(id);

        // 验证订单是否属于当前业务员
        if (order != null && order.getUser_id() == currentUser.getId()) {
            if (purchaseService.deletePurchaseOrder(id)) {
                request.getSession().setAttribute("successMessage", "订单删除成功！");
            } else {
                request.getSession().setAttribute("errorMessage", "订单删除失败：只能删除未审核的订单！");
            }
        } else {
            request.getSession().setAttribute("errorMessage", "订单删除失败：无权操作该订单！");
        }

        response.sendRedirect(request.getContextPath() + "/purchase/list");
    }

    private void saveOrder(HttpServletRequest request, HttpServletResponse response, User salesman)
            throws ServletException, IOException {
        PurchaseOrder order = new PurchaseOrder();
        order.setUser_id(salesman.getId());
        order.setV_id(Integer.parseInt(request.getParameter("vehicleId")));
        order.setQuantity(Integer.parseInt(request.getParameter("quantity")));
        order.setStatus(0); // 新订单状态设为未审核

        if (purchaseService.createPurchaseOrder(order)) {
            request.getSession().setAttribute("successMessage", "订单创建成功！");
        } else {
            request.getSession().setAttribute("errorMessage", "订单创建失败，请重试！");
        }

        response.sendRedirect(request.getContextPath() + "/purchase/list");
    }

    private void updateOrder(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        PurchaseOrder order = purchaseService.getPurchaseOrderById(id);
        User currentUser = (User) request.getSession().getAttribute("currentUser");

        if (order != null &&
                purchaseService.canEditOrder(id) &&
                order.getUser_id() == currentUser.getId()) {

            order.setV_id(Integer.parseInt(request.getParameter("vehicleId")));
            order.setQuantity(Integer.parseInt(request.getParameter("quantity")));

            if (purchaseService.updatePurchaseOrder(order)) {
                request.getSession().setAttribute("successMessage", "订单更新成功！");
            } else {
                request.getSession().setAttribute("errorMessage", "订单更新失败，请重试！");
            }
        } else {
            request.getSession().setAttribute("errorMessage", "订单更新失败：只能修改未审核的订单！");
        }

        response.sendRedirect(request.getContextPath() + "/purchase/list");
    }
}